<?php
require_once 'database21.php';

class Department extends Database {
    public function createDepartment($name) {
        try {
            $stmt = $this->conn->prepare("INSERT INTO departments (department_name) VALUES (:name)");
            $stmt->execute([':name' => $name]);
            return $this->conn->lastInsertId();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function getDepartments() {
        try {
            $stmt = $this->conn->prepare("SELECT * FROM departments");
            $stmt->execute();
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function getDepartment($id) {
        try {
            $stmt = $this->conn->prepare("SELECT * FROM departments WHERE department_id = :id");
            $stmt->execute([':id' => $id]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function updateDepartment($id, $name) {
        try {
            $stmt = $this->conn->prepare("UPDATE departments SET department_name = :name WHERE department_id = :id");
            $stmt->execute([ ':id' => $id, ':name' => $name]);
            return $stmt->rowCount();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function deleteDepartment($id) {
        try {
            // 检查是否有班级属于该系部
            $stmt = $this->conn->prepare("SELECT * FROM classes WHERE department_id = :id");
            $stmt->execute([':id' => $id]);

            if ($stmt->rowCount() > 0) {
                throw new Exception("无法删除, 该系部下有班级存在");
            }

            $stmt = $this->conn->prepare("DELETE FROM departments WHERE department_id = :id");
            $stmt->execute([ ':id' => $id]);
            return $stmt->rowCount();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        } catch (Exception $e) {
            die("错误: " . $e->getMessage());
        }
    }
}
?>